package cn.pping.service.impl;

import cn.pping.domain.*;
import cn.pping.dto.PullBlackDto;
import cn.pping.fegin.UaaFeignService;
import cn.pping.constants.RedisRegistConstant;
import cn.pping.dto.PhoneRegisterDto;
import cn.pping.dto.RedisRegisterDto;
import cn.pping.exception.GlobalEnumCode;
import cn.pping.mapper.UserMapper;
import cn.pping.query.UserQuery;
import cn.pping.result.JSONResult;
import cn.pping.service.IUserAccountService;
import cn.pping.service.IUserBaseInfoService;
import cn.pping.service.IUserGrowLogService;
import cn.pping.service.IUserService;
import cn.pping.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author director
 * @since 2022-08-27
 */
@Service
public class UserServiceImpl<selectPage> extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private UaaFeignService uaaFeignService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private IUserBaseInfoService userBaseInfoService;

    @Autowired
    private IUserGrowLogService userGrowLogService;

    @Autowired
    private IUserService userService;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void register(PhoneRegisterDto phoneRegisterDto) {
        // dto中的参数
        // 1.参数校验，使用JSR303完成
        String mobile = phoneRegisterDto.getMobile();
        String password = phoneRegisterDto.getPassword();
        Integer regChannel = phoneRegisterDto.getRegChannel();
        String smsCode = phoneRegisterDto.getSmsCode();
        // 获取手机验证码判断是否正确 拿到Key
        String key = String.format(RedisRegistConstant.PHONE_REGISTER_PREFIX, mobile);
        System.out.println(key);
        // 拿到value
        Object o = redisTemplate.opsForValue().get(key);
        System.out.println(o);
        // 判断手机号是否存在
        AssertUtil.isNotNull(o, GlobalEnumCode.CODE_EXPIRED_ERROR);
        // 不存在 吧得到的value转换为对象
        RedisRegisterDto code = (RedisRegisterDto) o;
        // 判断是否想到
        AssertUtil.isEqualsIgnoreCase(code.getCode(), smsCode, GlobalEnumCode.CODE_INCORRECT_ERROR);
        // 判断手机号是否注册过
        User user = selectByPhone(mobile);
        // 判断是都为空
        AssertUtil.isNull(user, GlobalEnumCode.USER_EXISTED_ERROR);

        // 保存LoginIn
        JSONResult jsonResult = saveLogin(mobile, password);
        // 通过结果判断是都成功
        AssertUtil.isTrue(jsonResult.isSuccess(), GlobalEnumCode.ERROR);
        // 保存user
        Long loginId = Long.valueOf(jsonResult.getData().toString());
        System.out.println("无" + loginId);
        AssertUtil.isNotNull(loginId, GlobalEnumCode.USER_REGISTER_ERROR);
        // 保存user
        User saveUser = saveUser(loginId, mobile);
        Long userId = saveUser.getId();
        AssertUtil.isNotNull(userId, GlobalEnumCode.USER_REGISTER_ERROR);
        // 保存其他表
        // 保存UserAccount相关表
        saveUserAccount(userId);

        // 保存UserBaseInfo相关表
        saveUserInfo(regChannel, userId);
        // 保存UserGrowLog相关表
//        saveUserGrow(userId);

    }


    private JSONResult saveLogin(String mobile, String password) {
        Login login = new Login();
        login.setUsername(mobile);
        login.setPassword(password);
        login.setType(1);
        login.setEnabled(true);
        // 保存login的信息
        JSONResult jsonResult = uaaFeignService.saveOrUpdate(login);
        return jsonResult;
    }

    private void saveUserGrow(Long userId) {
        UserGrowLog userGrowLog = new UserGrowLog();
        userGrowLog.setUserId(userId);
        userGrowLog.setCreateTime(new Date().getTime());
        userGrowLogService.insert(userGrowLog);
    }

    private void saveUserInfo(Integer regChannel, Long userId) {
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setCreateTime(new Date().getTime());
        userBaseInfo.setId(userId);
        userBaseInfoService.insert(userBaseInfo);
    }

    private void saveUserAccount(Long userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userId);
        // 应该调用短信接口发送短信
        userAccount.setPassword("123456");
        userAccount.setCreateTime(new Date().getTime());
        userAccountService.insert(userAccount);
    }

    private User saveUser(Long loginId, String mobile) {
        User user = new User();
        user.setPhone(mobile);
        user.setNickName(mobile);
        user.setCreateTime(new Date().getTime());
        user.setLoginId(loginId);
        // mybatis-plus会自动帮我们返回主键
        insert(user);
        return user;
    }

    private User selectByPhone(String mobile) {
        // wapper的条件构造器
        EntityWrapper<User> objectEntityWrapper = new EntityWrapper<>();
        objectEntityWrapper.eq("phone", mobile);
        return selectOne(objectEntityWrapper);
    }

    @Override
    public JSONResult pullBlack(PullBlackDto pullBlackDto) {
        // 根据传过来的对象找到对应的User
        // 设置type和原因
        Long userId = pullBlackDto.getUserId();
        User user = selectByUserId(userId);
//        user.setType(0);
//        user.setReason(pullBlackDto.getReason());
        userService.updateById(user);
        return JSONResult.success();
    }

    private User selectByUserId(Long userId) {
        // wapper的条件构造器
        EntityWrapper<User> objectEntityWrapper = new EntityWrapper<>();
        objectEntityWrapper.eq("id", userId);
        return selectOne(objectEntityWrapper);
    }


}

